<template>
  <div class="app-container">
    <!-- 教师搜索表单（简化版） -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师工号" prop="teacherCode">
        <el-input
            v-model="queryParams.teacherCode"
            placeholder="请输入教师工号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-col :span="2">
      <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImportTutor"
      >导入导师匹配</el-button>
    </el-col>
    <el-col :span="2">
      <el-button
          type="info"
          plain
          icon="Document"
          @click="handleDownloadTemplate"
      >下载导入模板</el-button>
    </el-col>
    <!-- 教师列表（仅保留查看功能） -->
    <el-card>
      <div slot="header">
        <strong>教师列表</strong>
      </div>
      <el-table v-loading="loading" :data="teacherandstudentList" @selection-change="handleTeacherSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="教师工号" align="center" prop="teacherCode" />
        <el-table-column label="所属学院" align="center" prop="collegeId" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="研究领域" align="center" prop="researchField" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="User" @click="handleViewStudents(scope.row)">查看学生</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 学生子表 (只有选择教师后才显示) -->
    <el-card v-if="selectedTeacher" class="mt-4">
      <div slot="header">
        <strong>
          学生列表 (当前教师: {{ selectedTeacher.name }} - {{ selectedTeacher.teacherCode }})
        </strong>
        <el-button
            type="text"
            size="small"
            @click="clearTeacherSelection"
            class="ml-4"
        >
          清除选择
        </el-button>
      </div>

      <!-- 学生搜索表单 -->
      <el-form :model="queryParamstudent" ref="studentQueryRef" :inline="true" label-width="68px" class="mb-4">
        <el-form-item label="学号" prop="studentId">
          <el-input
              v-model="queryParamstudent.studentId"
              placeholder="请输入学号"
              clearable
              @keyup.enter="handleStudentQuery"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="studentName">
          <el-input
              v-model="queryParamstudent.studentName"
              placeholder="请输入姓名"
              clearable
              @keyup.enter="handleStudentQuery"
          />
        </el-form-item>
        <el-form-item label="专业" prop="studentZy">
          <el-input
              v-model="queryParamstudent.studentZy"
              placeholder="请输入专业"
              clearable
              @keyup.enter="handleStudentQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleStudentQuery">搜索学生</el-button>
          <el-button icon="Refresh" @click="resetStudentQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 学生操作按钮（仅保留新增功能） -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAddStudent"
          >新增学生</el-button>
        </el-col>
      </el-row>

      <!-- 学生表格 -->
      <el-table v-loading="studentLoading" :data="studentList">
        <el-table-column label="学号" align="center" prop="studentId" />
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column label="民族" align="center">
          <template #default="scope">
            {{ getNationName(scope.row.studentNation) }}
          </template>
        </el-table-column>

        <el-table-column label="性别" align="center">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.studentSex" />
          </template>
        </el-table-column>

        <el-table-column label="院系" align="center">
          <template #default="scope">
            {{ getCollegeName(scope.row.studentYx) }}
          </template>
        </el-table-column>
        <!-- 学生表格中的专业列 -->
        <el-table-column label="专业" align="center">
          <template #default="scope">
            {{ getMajorName(scope.row.studentZy) }}
          </template>
        </el-table-column>
        <el-table-column label="研究方向" align="center" prop="studentYjfx" />
        <el-table-column label="年级" align="center" prop="studentNj" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
<!--            <el-button link type="primary" icon="Edit" @click="handleUpdateStudent(scope.row)">修改</el-button>-->
            <el-button link type="primary" icon="Delete" @click="handleDeleteStudent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="studentTotal>0"
          :total="studentTotal"
          v-model:page="queryParamstudent.pageNum"
          v-model:limit="queryParamstudent.pageSize"
          @pagination="getStudentList"
      />
    </el-card>

    <!-- 学生添加或修改对话框 -->
    <el-dialog :title="studentTitle" v-model="studentOpen" width="500px" append-to-body>
      <el-form ref="studentRef" :model="studentForm" :rules="studentRules" label-width="80px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" placeholder="请输入学号" @change="getStudentNameByStudentXh"/>
        </el-form-item>
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="studentForm.studentName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="民族" prop="studentNation">
          <el-select v-model="studentForm.studentNation" placeholder="请选择民族" filterable>
            <el-option v-for="item in originnationlist"
                       :key="item.id"
                       :label="item.nadictLabel"
                       :value="item.nadictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="性别" prop="studentSex">
          <el-select v-model="studentForm.studentSex" placeholder="请选择性别" filterable>
            <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="院系" prop="studentYx">
          <el-select v-model="studentForm.studentYx" placeholder="请选择院系" filterable>
            <el-option
                v-for="item in yxList"
                :key="item.collegeCode"
                :label="item.collegeName"
                :value="item.collegeCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="studentZy">
          <el-select v-model="studentForm.studentZy" placeholder="请选择专业" filterable>
            <el-option
                v-for="item in zyZlist"
                :key="item.majorCode"
                :label="item.majorName"
                :value="item.majorCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="研究方向码" prop="studentYjfxm">
          <el-input v-model="studentForm.studentYjfxm" placeholder="请输入研究方向码" />
        </el-form-item>
        <el-form-item label="研究方向" prop="studentYjfx">
          <el-input v-model="studentForm.studentYjfx" placeholder="请输入研究方向" />
        </el-form-item>
        <el-form-item label="年级" prop="studentNj">
          <el-input v-model="studentForm.studentNj" placeholder="请输入年级" />
        </el-form-item>
        <el-form-item label="导师编号" prop="studentDsbh">
          <el-input v-model="studentForm.studentDsbh" placeholder="请输入导师编号" :value="selectedTeacher?.teacherCode" readonly />
        </el-form-item>
        <el-form-item label="导师姓名" prop="studentDs">
          <el-input v-model="studentForm.studentDs" placeholder="请输入导师姓名" :value="selectedTeacher?.name" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStudentForm">确 定</el-button>
          <el-button @click="cancelStudent">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增：学生导师匹配导入对话框 -->
    <el-dialog
        title="导入学生导师匹配"
        v-model="importDialogVisible"
        width="500px"
        append-to-body
    >
      <el-form ref="importForm" :model="importForm" label-width="100px">
        <el-form-item label="上传文件">
          <!-- 确保模板中的绑定正确 -->
          <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :http-request="handleFileUpload"
              :on-change="handleFileChange"
              :before-upload="beforeFileUpload"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleFileExceed"
              accept=".xlsx,.xls"
          >
            <el-button type="primary" icon="Upload">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip text-danger">
                仅支持.xlsx、.xls格式文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="importProgress > 0 && importProgress < 100">
          <div class="progress-container">
            <el-progress :percentage="importProgress" stroke-width="6"></el-progress>
            <div class="progress-text">
              {{ importProgress }}% 已完成
              <span v-if="importStatusMsg">{{ importStatusMsg }}</span>
            </div>
          </div>
        </el-form-item>
        <!-- 在导入对话框中添加重复学生信息显示区域 -->
        <el-form-item v-if="importProgress === 100 && duplicateStudents.length > 0">
          <div class="duplicate-info">
            <div class="info-title">以下学生将更新导师信息或导入重复：</div>
            <el-table :data="duplicateStudents" size="small" max-height="200" style="width: 100%">
              <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
              <el-table-column prop="studentName" label="姓名" width="100"></el-table-column>
              <el-table-column prop="oldTeacher" label="原导师"></el-table-column>
              <el-table-column prop="newTeacher" label="新导师"></el-table-column>
            </el-table>
          </div>
        </el-form-item>


        <el-form-item v-if="importProgress === 100">
          <div v-if="importSuccess" class="success-message">
            <el-icon color="green"><Check /></el-icon>
            导入成功，共处理 {{ successCount }} 条数据，失败 {{ failureCount }} 条
          </div>
          <div v-else class="error-message">
            <el-icon color="red"><Close /></el-icon>
            导入失败: {{ importStatusMsg }}
          </div>
          <el-button
              v-if="failureCount > 0"
              type="text"
              @click="handleDownloadFailures"
              class="download-failures"
          >
            <el-icon><Download /></el-icon> 下载失败数据
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 修改模板中的对话框底部按钮部分 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelImport">取消</el-button>
          <el-button
              type="primary"
              @click="submitImport"
              :disabled="fileList.length === 0 || isImporting"
              v-if="!importSuccess || importProgress < 100"
          >
            <el-icon v-if="isImporting"><Loading /></el-icon>
            <span v-else>确认导入</span>
          </el-button>

          <!-- 添加导入成功后的确认按钮 -->
          <el-button
              type="primary"
              @click="confirmAndClose"
              v-if="importSuccess && importProgress >= 100"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>




<script setup name="TeacherStudentSimplified">
import { onUnmounted } from 'vue';
import { listAllTeacher } from "@/api/teacher/teacher.js"
import {
  generateImportBatchNo,
  importStudentTutor,
  queryImportProgress,
  downloadFailureData,
  listAllStudentManger,
  getStudentManger,
  delStudentManger,
  addStudentManger,
  updateStudentManger,
  getStudentInfoByStudentXh
} from "@/api/student/studentManger.js"
import {listNation} from "@/api/dictionaries/nation.js"
import { listCollege } from "@/api/college/college.js"
import { listPoliticalstatus } from "@/api/dictionaries/politicalstatus.js"
import {listMajor} from "@/api/major/major.js";
import {loadAllParams} from "@/api/page.js"
const { proxy } = getCurrentInstance()
const { sys_user_sex } = proxy.useDict( 'sys_user_sex');
// 教师相关数据
const teacherandstudentList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const selectedTeacher = ref(null)

// 学生相关数据
const studentList = ref([])
const studentOpen = ref(false)
const studentLoading = ref(false)
const studentTotal = ref(0)
const studentTitle = ref("")
const duplicateStudents = ref([]); // 用于存储重复学生信息
// 新增：学生导师导入相关变量
const importDialogVisible = ref(false);
const fileList = ref([]);
const currentFile = ref(null);
const importForm = reactive({});
const isImporting = ref(false);
const importProgress = ref(0);
const importStatusMsg = ref('');
const importSuccess = ref(false);
const successCount = ref(0);
const failureCount = ref(0);
const currentBatchNo = ref('');
const progressInterval = ref(null);
// 数据模型
const data = reactive({
  studentForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    teacherCode: null,
    collegeId: null,
  },
  queryParamstudent: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    studentName: null,
    studentZy: null,
    studentDsbh: null, // 导师编号，用于关联查询
  },
  studentRules: {
    studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
    studentName: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
  }
})

const { queryParams, queryParamstudent, studentForm, studentRules } = toRefs(data)

/** 查询教师列表 */
function getList() {
  loading.value = true
  listAllTeacher(queryParams.value).then(response => {
    teacherandstudentList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 新增：确认并关闭弹窗的方法
function confirmAndClose() {
  importDialogVisible.value = false;
  resetImportForm();
}

function getNationName(nationCode) {
  if (!nationCode || !originnationlist.value) return '';

  const nation = originnationlist.value.find(item => item.nadictValue === nationCode);
  return nation ? nation.nadictLabel : nationCode;
}

function getCollegeName(collegeCode) {
  if (!collegeCode || !yxList.value) return '';

  const college = yxList.value.find(item => item.collegeCode === collegeCode);
  return college ? college.collegeName : collegeCode;
}

function getMajorName(majorCode) {
  if (!majorCode || !zyZlist.value) return '';

  const major = zyZlist.value.find(item => item.majorCode === majorCode);
  return major ? major.majorName : majorCode;
}

/** 查询选中教师的学生列表 */
function getStudentList() {
  if (!selectedTeacher.value) return

  studentLoading.value = true
  // 设置查询参数中的导师编号，关联查询
  queryParamstudent.value.studentDsbh = selectedTeacher.value.teacherCode

  listAllStudentManger(queryParamstudent.value).then(response => {
    studentList.value = response.rows
    studentTotal.value = response.total
    studentLoading.value = false
  })
}
const originpaList = ref([]);
const originnationlist = ref([]);

/** 获取民族列表（返回Promise便于异步控制） */
function getNationalities() {
  return new Promise((resolve, reject) => {
    listNation(loadAllParams).then(response => {
      originnationlist.value = response.rows;
      resolve();
    }).catch(error => {
      console.error("民族列表加载失败：", error);
      reject(error); // 传递错误，中断初始化
    });
  });
}

/** 获取政治面貌列表（返回Promise便于异步控制） */
function getPoliticalAffiliations() {
  return new Promise((resolve, reject) => {
    listPoliticalstatus(loadAllParams).then(response => {
      originpaList.value = response.rows;
      resolve();
    }).catch(error => {
      console.error("政治面貌列表加载失败：", error);
      reject(error);
    });
  });
}
const yxList = ref([]);
/** 获取学院列表（返回Promise便于异步控制） */
function getColleges() {
  return new Promise((resolve, reject) => {
    listCollege(loadAllParams).then(response => {
      yxList.value = response.rows;
      console.log(yxList.value);
      resolve();
    }).catch(error => {
      console.error("学院列表加载失败：", error);
      reject(error);
    });
  });
}
const zyZlist = ref([]);
/** 获取专业列表（返回Promise便于异步控制） */
function getlistMajor() {
  return new Promise((resolve, reject) => {
    listMajor(loadAllParams).then(response => {
      zyZlist.value = response.rows;
      resolve();
    }).catch(error => {
      console.error("专业列表加载失败：", error);
      reject(error);
    });
  });
}
/** 通过学号获取学生姓名 */
function getStudentNameByStudentXh() {
  getStudentInfoByStudentXh(studentForm.value.studentId).then(response => {
    studentForm.value.studentName = response.data.studentName
  })
}

/** 教师搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 学生搜索按钮操作 */
function handleStudentQuery() {
  queryParamstudent.value.pageNum = 1
  getStudentList()
}

/** 教师重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 学生重置按钮操作 */
function resetStudentQuery() {
  proxy.resetForm("studentQueryRef")
  // 保留导师编号条件
  const teacherCode = queryParamstudent.value.studentDsbh
  queryParamstudent.value = {
    ...queryParamstudent.value,
    studentId: null,
    studentName: null,
    studentZy: null,
    studentDsbh: teacherCode
  }
  handleStudentQuery()
}

/** 教师选择变更 */
function handleTeacherSelectionChange(selection) {
  // 选择单个教师时加载其学生
  if (selection.length === 1) {
    selectedTeacher.value = selection[0];
    getStudentList();
  } else if (selection.length === 0) {
    selectedTeacher.value = null;
  }
}

/** 查看指定教师的学生 */
function handleViewStudents(teacher) {
  selectedTeacher.value = teacher;
  getStudentList();
  // 滚动到学生表格
  setTimeout(() => {
    document.querySelector('.mt-4').scrollIntoView({ behavior: 'smooth' });
  }, 100);
}

/** 清除教师选择 */
function clearTeacherSelection() {
  selectedTeacher.value = null;
  studentList.value = [];
  studentTotal.value = 0;
}

/** 学生表单重置 */
function resetStudent() {
  studentForm.value = {
    id: null,
    studentId: null,
    studentName: null,
    studentNation: null,
    studentSex: null,
    studentYx: null,
    studentZy: null,
    studentYjfxm: null,
    studentYjfx: null,
    studentNj: null,
    studentDsbh: selectedTeacher.value?.teacherCode || null,
    studentDs: selectedTeacher.value?.name || null,
  }
  proxy.resetForm("studentRef")
}

/** 新增学生 */
function handleAddStudent() {
  if (!selectedTeacher.value) {
    proxy.$modal.msgWarning('请先选择一位教师')
    return
  }
  resetStudent()
  studentOpen.value = true
  studentTitle.value = "添加学生"
}

/** 修改学生 */
function handleUpdateStudent(row) {
  resetStudent()
  studentOpen.value = true
  studentTitle.value = "修改学生"
  // 获取学生详情
  getStudentManger(row.studentId).then(response => {
    studentForm.value = response.data
  })
}

/** 解除学生与当前教师的关联（清空导师字段） */
function handleDeleteStudent(row) {
  // 验证学号是否存在
  if (!row.studentId) {
    proxy.$modal.msgError('学生学号不存在，无法解除关联');
    return;
  }

  // 先通过学号查询获取学生id
  proxy.$modal.confirm(`确定要将学生【${row.studentName}】与当前教师解除关联吗？`).then(() => {
    // 第一步：查询学生id
    return getStudentInfoByStudentXh(row.studentId);
  }).then(response => {
    // 检查查询结果是否包含id
    const studentData = response.data;
    if (!studentData || !studentData.id) {
      proxy.$modal.msgError('未查询到学生的完整信息，无法解除关联');
      return Promise.reject(new Error('缺少学生id')); // 中断后续操作
    }

    // 第二步：使用查询到的id执行更新操作
    const updatedStudent = {
      id: studentData.id,  // 使用查询到的id
      studentDsbh: null,   // 清空导师编号
      studentDs: null      // 清空导师姓名
    };
    return updateStudentManger(updatedStudent);
  }).then(() => {
    getStudentList();  // 刷新学生列表
    proxy.$modal.msgSuccess('已成功解除关联');
  }).catch(error => {
    // 忽略用户取消确认的情况，只处理真实错误
    if (error && error.message !== 'cancel') {
      proxy.$modal.msgError('解除关联失败：' + (error.message || '未知错误'));
    }
  });
}

/** 提交学生表单 */
function submitStudentForm() {
  proxy.$refs["studentRef"].validate(valid => {
    if (valid) {
      // 确保学生关联到当前选中的教师
      studentForm.value.studentDsbh = selectedTeacher.value.teacherCode;
      studentForm.value.studentDs = selectedTeacher.value.name;

      // 异步获取id，并在获取完成后提交
      getStudentInfoByStudentXh(studentForm.value.studentId).then(response => {
        console.log("获取到的id：" + response.data.id);
        studentForm.value.id = response.data.id;

        // 确认id已赋值后再执行提交
        if (studentForm.value.studentId != null) {
          updateStudentManger(studentForm.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            studentOpen.value = false;
            getStudentList();
          });
        } else {
          addStudentManger(studentForm.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            studentOpen.value = false;
            getStudentList();
          });
        }
      }).catch(error => {
        proxy.$modal.msgError("获取学生信息失败：" + error.message);
      });
    }
  });
}

/** 取消学生操作 */
function cancelStudent() {
  studentOpen.value = false
  resetStudent()
}
init();
// 核心：初始化函数（异步顺序执行）
async function init() {
  loading.value = true; // 初始化期间显示整体加载状态
  try {
    // 1. 先加载所有依赖的字典数据（并行执行，提升速度）
    await Promise.all([
      getNationalities(),
      getPoliticalAffiliations(),
      getColleges(),
      getlistMajor(),
      // getTeacher(),
      // getIdCard()
    ]);
    // 2. 依赖数据加载完成后，加载学生列表
    await getList();

  } catch (error) {
    console.error("初始化失败：", error);
    proxy.$modal.msgError("页面初始化失败，请刷新重试");
  } finally {
    loading.value = false; // 无论成功失败，都结束初始化加载
  }
}
// 新增：处理导入对话框打开
function handleImportTutor() {
  resetImportForm();
  importDialogVisible.value = true;
}

// 新增：重置导入表单
function resetImportForm() {
  fileList.value = [];
  currentFile.value = null;
  isImporting.value = false;
  importProgress.value = 0;
  importStatusMsg.value = '';
  importSuccess.value = false;
  successCount.value = 0;
  failureCount.value = 0;
  duplicateStudents.value = []; // 重置重复学生列表
  currentBatchNo.value = '';
  if (progressInterval.value) {
    clearInterval(progressInterval.value);
    progressInterval.value = null;
  }
}

// 新增：取消导入
function cancelImport() {
  resetImportForm();
  importDialogVisible.value = false;
}

// 1. 修改 fileList 定义（从 ref 改为 reactive）
// 替代原 const fileList = ref([]);

// 2. 修复 handleFileChange 函数（用数组方法更新，保留响应式）
// 修复：应该直接操作 ref 的 value
function handleFileChange(file, uploadedFileList) {
  fileList.value = [{
    ...file,
    status: 'ready'
  }];
  currentFile.value = file.raw;
}

// 3. 修复 handleFileRemove 函数（同样用 splice 清空）
// 修复：应该操作 ref 的 value
function handleFileRemove() {
  fileList.value = [];
  currentFile.value = null;
}

// 改进文件上传前验证
function beforeFileUpload(file) {
  // 更详细的文件类型检查
  const fileExt = file.name.split('.').pop().toLowerCase();
  const isExcel = ['xlsx', 'xls'].includes(fileExt);

  // 更详细的文件大小检查
  const fileSizeMB = file.size / 1024 / 1024;
  const isLt2M = fileSizeMB < 2;

  console.log(`文件验证 - 名称: ${file.name}, 类型: ${file.type}, 扩展名: ${fileExt}, 大小: ${fileSizeMB.toFixed(2)}MB`);

  if (!isExcel) {
    proxy.$modal.msgError('上传文件只能是.xlsx或.xls格式!');
    return false;
  }
  if (!isLt2M) {
    proxy.$modal.msgError(`上传文件大小不能超过2MB! 当前文件大小: ${fileSizeMB.toFixed(2)}MB`);
    return false;
  }

  // 检查文件是否为空
  if (file.size === 0) {
    proxy.$modal.msgError('不能上传空文件!');
    return false;
  }

  return true;
}

// 新增：自定义文件上传处理（实际在submitImport中处理）
function handleFileUpload() {
  // 空实现，因为我们在submitImport中手动处理上传
}

// 新增：提交导入
// 修复：提交导入（核心逻辑）
// 改进提交导入函数
async function submitImport() {
  if (!currentFile.value || fileList.value.length === 0) {
    proxy.$modal.msgWarning('请先选择要导入的文件');
    return;
  }

  try {
    isImporting.value = true;
    importStatusMsg.value = '正在准备导入...';

    // 生成导入批次号
    const batchRes = await generateImportBatchNo();
    currentBatchNo.value = batchRes.data;
    if (!currentBatchNo.value) {
      throw new Error('获取导入批次号失败，请重试');
    }

    // 构建FormData - 增加错误处理
    const formData = new FormData();
    try {
      formData.append('file', currentFile.value);
      formData.append('batchNo', currentBatchNo.value);
      // 打印FormData内容用于调试
      console.log('FormData内容:');
      formData.forEach((value, key) => {
        console.log(`${key}: ${key === 'file' ? value.name : value}`);
      });
    } catch (formError) {
      throw new Error(`构建上传数据失败: ${formError.message}`);
    }

    // 调用上传接口 - 增加超时处理
    const uploadPromise = importStudentTutor(formData);
    // 设置5分钟超时
    const timeoutPromise = new Promise((_, reject) =>
        setTimeout(() => reject(new Error('上传超时，请检查网络或文件大小')), 300000)
    );

    //  raced between upload and timeout
    await Promise.race([uploadPromise, timeoutPromise]);

    // 开始查询导入进度
    importStatusMsg.value = '正在导入数据...';
    await checkImportProgress();
    // 动态调整查询频率，开始频繁些，后来降低频率
    let intervalTime = 1000; // 开始1秒一次
    progressInterval.value = setInterval(() => {
      checkImportProgress();
      // 20秒后变为3秒一次，40秒后变为5秒一次
      if (importProgress.value > 50 && intervalTime < 3000) {
        intervalTime = 3000;
        clearInterval(progressInterval.value);
        progressInterval.value = setInterval(checkImportProgress, intervalTime);
      } else if (importProgress.value > 80 && intervalTime < 5000) {
        intervalTime = 5000;
        clearInterval(progressInterval.value);
        progressInterval.value = setInterval(checkImportProgress, intervalTime);
      }
    }, intervalTime);

  } catch (error) {
    console.error('导入失败详情:', error);
    // 更详细的错误信息
    let errorMsg = '导入失败，请重试';
    if (error.response) {
      // 服务器返回错误
      errorMsg = `服务器错误: ${error.response.data?.msg || '未知错误'}`;
      console.error('服务器响应错误:', error.response);
    } else if (error.request) {
      // 无响应
      errorMsg = '未收到服务器响应，请检查网络连接';
    } else {
      // 其他错误
      errorMsg = error.message;
    }
    importStatusMsg.value = errorMsg;
    isImporting.value = false;
    // 显示错误详情对话框
    proxy.$modal.error({
      title: '导入失败',
      content: errorMsg,
      showCancelButton: false
    });
  }
}

// 改进检查导入进度函数
async function checkImportProgress() {
  if (!currentBatchNo.value) return;

  try {
    const progressRes = await queryImportProgress(currentBatchNo.value);
    const progressData = progressRes.data;

    if (!progressData) {
      throw new Error('进度数据格式不正确');
    }

    // 使用后端实际返回的字段，而不是不存在的percentage字段
    importProgress.value = progressData.progress || 0;
    importStatusMsg.value = progressData.message || `正在处理...(${importProgress.value}%)`;

    // 如果导入完成（根据后端实际返回的状态和进度判断）
    if (progressData.progress >= 100 || progressData.status === '完成') {
      clearInterval(progressInterval.value);
      progressInterval.value = null;
      isImporting.value = false;

      // 根据后端实际返回的字段设置成功状态
      importSuccess.value = progressData.failCount === 0;
      successCount.value = progressData.successCount || 0;
      failureCount.value = progressData.failCount || 0;
      // 处理重复学生信息
      if (progressData.duplicateStudents && Array.isArray(progressData.duplicateStudents)) {
        duplicateStudents.value = progressData.duplicateStudents;
      } else {
        duplicateStudents.value = [];
      }
      if (importSuccess.value) {
        importStatusMsg.value = `导入成功，共处理 ${successCount.value} 条，失败 ${failureCount.value} 条`;
        getList(); // 刷新学生列表
      } else {
        importStatusMsg.value = progressData.errorMsg || '导入过程中发生错误';
      }
    }
  } catch (error) {
    console.error('查询进度失败:', error);
    importStatusMsg.value = `查询进度失败: ${error.message}`;
    // 3次失败后停止查询，但保留界面状态
    if (window.progressFailureCount) {
      window.progressFailureCount++;
      if (window.progressFailureCount >= 3) {
        clearInterval(progressInterval.value);
        progressInterval.value = null;
        isImporting.value = false;
        importStatusMsg.value = '多次查询进度失败，请手动刷新查看结果';
      }
    } else {
      window.progressFailureCount = 1;
    }
  }
}


// 新增：文件超出限制时提示
function handleFileExceed(files, fileList) {
  proxy.$modal.msgWarning(`最多只能选择1个文件，已自动过滤多余文件`);
}
// 新增：下载失败数据
function handleDownloadFailures() {
  if (!currentBatchNo.value) {
    proxy.$modal.msgWarning('没有批次号，无法下载');
    return;
  }

  downloadFailureData(currentBatchNo.value).then(response => {
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `导师匹配导入失败数据_${currentBatchNo.value}.xlsx`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }).catch(error => {
    console.error('下载失败数据出错:', error);
    proxy.$modal.msgError('下载失败，请重试');
  });
}

//新增：下载导入模板
// function handleDownloadTemplate() {
//   downloadTutorTemplate().then(response => {
//     const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
//     const url = window.URL.createObjectURL(blob);
//     const a = document.createElement('a');
//     a.href = url;
//     a.download = '学生导师匹配导入模板.xlsx';
//     document.body.appendChild(a);
//     a.click();
//     window.URL.revokeObjectURL(url);
//     document.body.removeChild(a);
//   }).catch(error => {
//     console.error('下载模板出错:', error);
//     proxy.$modal.msgError('下载模板失败，请重试');
//   });
// }
function handleDownloadTemplate() {
  // 原错误：this.download → 修正为 proxy.download（RuoYi 框架方法挂载在实例上）
  proxy.download('/student/studentManger/downloadTutorTemplate', {},
      `学生导师指定导入模板_${new Date().getTime()}.xlsx`);
}

// 组件卸载时清理资源（防止内存泄漏）
// 组件卸载时清理资源
onUnmounted(() => {
  if (progressInterval.value) {
    clearInterval(progressInterval.value);
  }
});
// 初始化加载教师列表
getList();

</script>
<style scoped>
.duplicate-info {
  margin-top: 16px;
  padding: 16px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  width: 500px;
  margin-left: -70px;
  margin-right: 5%;
}

.info-title {
  font-weight: bold;
  color: #67c23a;
  margin-bottom: 12px;
  font-size: 14px;
  border-bottom: 1px dashed #ccc;
  padding-bottom: 6px;
}





</style>

